<template>
	<view class="chat-container">
		<tn-nav-bar fixed alpha isBack>
			旅行规划大师
		</tn-nav-bar>
		<view class="conversation" :style="{paddingTop: vuex_custom_bar_height+'px'}">
			<scroll-view
			  class="conversation__scroll-view"
			  :class="{'conversation__scroll-view--auto': scrollViewStyle.height === 'auto'}"
			  :style="[scrollViewStyle]"
			  :scroll-y="scrollViewStyle.height !== 'auto'"
			>
				<view class="chat-area">
					<view v-for="message in messageList" class="message-content tn-padding-left-lg tn-padding-right-lg tn-padding-bottom-lg">
							<question-vue v-if="message.type === 'question'" :message="message"></question-vue>
							<answer-vue v-if="message.type === 'answer'" :message="message" :replying="replying"></answer-vue>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="chat-input-layout">
			<view class="shortcut-bar"></view>
			<view class="chat-input tn-flex">
				<tn-input v-model="sendMsg" class="tn-flex-1 tn-padding-left-lg tn-padding-top-sm" :autoHeight="true" placeholder="发送消息..." />
				<view class="file-btn tn-flex tn-flex-row-center tn-flex-col-center tn-text-xxl">
					<text class="tn-icon-add-circle"></text>
				</view>
				<view class="send-btn tn-flex tn-flex-row-center tn-flex-col-center tn-text-xxl" @click="handleSendMessage">
					<view class="fill-wrap tn-flex tn-flex-row-center tn-flex-col-center" :class="{ 'ready': !!sendMsg }">
						<text class="tn-icon-plane-fill"></text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import questionVue from './components/question.vue'
	import answerVue from './components/answer.vue'
	import { conversationCreate  } from '@/api/coze.js'
	import wxConfig from '@/common/config.js'
	export default {
		components: {
			questionVue,
			answerVue
		},
		data() {
			return {
				botId: '', // 智能体
				conversationId: '', // 当前会话ID
				scrollViewStyle: {
					height: 0
				},
				sendMsg: '',
				messageList: [],
				replying: false, // 回复状态
			}
		},
		onLoad(params) {
			console.log('onLoad', params)
			this.botId = params.botId
		},
		onReady() {
			this.getHeight()
			this.conversationCreateInterface()
		},
		methods: {
			// 创建新会话
			conversationCreateInterface() {
				conversationCreate().then(res => {
					if(res && res.success) {
						this.conversationId = res.data.id
					}
				})
			},
			getHeight() {
				uni.getSystemInfo({
				  success: (systemInfo) => {
						console.log('systemInfo', systemInfo)
						const navBarHeight = this.vuex_custom_bar_height
						const containerBaseHeight = systemInfo.safeArea.height
						this.scrollViewStyle.height = (containerBaseHeight - navBarHeight) + systemInfo.statusBarHeight + 'px'
						console.log(containerBaseHeight, navBarHeight, systemInfo.statusBarHeight)
					}
				})
			},
			// 发送消息
			handleSendMessage() {
				if(this.replying) {
					return
				}
				this.replying = true
				this.messageList.push({
					type: 'question',
					content: this.sendMsg
				})
				// 回复占位
				this.messageList.push({
					type: 'answer',
					flag: 'current',
					content: ''
				})
				this.sendChatInterface()
			},
			sendChatInterface() {
				let params =  {
					msg: this.sendMsg,
					conversationId: this.conversationId,
					botId: this.botId
				}
				this.sendMsg = ''
				this.sendChatStream(params)
				
			},
			// 流式请求接口
			sendChatStream(params) {
				console.log('params', params)
			    return new Promise (resolve => {
						const realThis = this
						const requestTask = uni.request({
								url: wxConfig.urlConfig + '/chat-stream',
								timeout: 10 * 60 * 1000,
								responseType: 'text',
								method: 'post',
								enableChunked: true,  //配置这里
								data: params,
								success: response => {
										console.log('response', response)
								},
								fail: error => {}
						})
						requestTask.onHeadersReceived(function(res) {
								console.log(res.header);
						});
						// 这里监听消息
						requestTask.onChunkReceived(function(res) {
							try{
								let decoder = new TextDecoder('utf-8');
								let text = decoder.decode(new Uint8Array(res.data));
								console.log('text', text)
								// 按 'event:' 分割字符串
								const parts = text.split('event:').filter(Boolean).map(part => part.trim());
								
								// 处理每个部分，提取 event 和 data
								const messages = parts.map(part => {
								  const [eventPart, dataPart] = part.split('\n');
								  return {
								    event: eventPart,
								    data: JSON.parse(dataPart.replace('data:', '').trim())
								  };
								});
								messages.forEach(msg => {
									if(msg.event === 'conversation.message.delta') {
										realThis.messageList[realThis.messageList.length - 1].content += msg.data.content
									} else if (msg.event === 'done') {
										console.log('我来结束了', msg)
										realThis.replying = false
										realThis.messageList.forEach(item => {
											if(item.flag === 'current') {
												delete item.flag
											}
										})
									}
								})
							}catch(e){
								//TODO handle the exception
								realThis.replying = false
							}
						})
			    })
			},
		}
	}
</script>

<style lang="scss" scoped>
	.chat-area {
		padding-top: 30rpx;
		padding-bottom: 150rpx;
		border-top: 2rpx solid #38374329;
	}
	.chat-input-layout {
		width: 100%;
		position: fixed;
		padding: 0 40rpx;
		bottom: env(safe-area-inset-bottom);
		background: linear-gradient(to bottom, transparent 0%, white 50%);
		.shortcut-bar {
			height: 100rpx;
		}
		.chat-input {
			height: 100rpx;
			background-color: #fff;
			border-radius: 50rpx;
			border: 2rpx solid #0607091a;
			.file-btn {
				width: 100rpx;
				position: relative;
				&::before {
					content: '';
					height: 30rpx;
					width: 2rpx;
					background-color: #0607091a;
					position: absolute;
					right: 0;
					top: 40rpx;
				}
			}
			.send-btn {
				width: 120rpx;
				.fill-wrap {
					width: 58rpx;
					height: 58rpx;
					border-radius: 50%;
					background-color: #f3f5fc;
					color: rgb(198, 198, 198);
					&.ready {
						background-color: rgb(53, 107, 253);
						color: rgb(255, 255, 255);
					}
				}
			}
		}
	}
</style>